﻿<!DOCTYPE html>
<html>
<head>
    <title>时间域设置</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="../../resources/lib/bui/css/dpl-min.css" rel="stylesheet" type="text/css" />
    <link href="../../resources/lib/bui/css/bui-min.css" rel="stylesheet" type="text/css" />


    <style type="text/css">
        .week {
            /*height: 20px;*/
        }
        .week input {
            margin-top: 4px;
            margin-left: 2px;
        }
        .week label {
            margin-left: 10px;
        }
    </style>
</head>
<body>


<div style="padding: 10px;">
    <div>
        <a class="button button-primary" onclick="addGroup()">新建组</a>
        <a class="button button-primary" onclick="copyGroup()">复制组</a>
        <a class="button button-primary" onclick="removeGroup()">删除组</a>
        <a class="button button-primary" onclick="updateGroup()">更新</a>
    </div>

    <div class="row" style="padding-top: 10px;">
        <div class="span4">
            <div id="time_group_list">
            </div>
        </div>
        <div class="span16">
            <form id="time_group_form" action="" class="form-horizontal">
                <div class="row">
                    <div class="control-group span8">
                        <label class="control-label" style="width: 90px;"><s>*</s>时间组名称：</label>
                        <div class="controls">
                            <input name="name" type="text" class="input-small" data-rules="{required : true}">
                        </div>
                    </div>
                    <div class="control-group span8">
                        <label class="control-label" style="width: 90px;">节假日组：</label>
                        <div class="controls">
                            <select class="input-small" name="holiday_id">
                                <option value="-1">无</option>
                                <option>组1</option>
                            </select>
                            <label class="checkbox"><input type="checkbox">节假日取反<i class=""></i></label>
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" style="width: 90px;">有效日期：</label>
                    <div class="controls">
                        <input class="calendar" name="active" type="text" data-rules="{required : true}" data-messages="{required:'生效日期不能为空'}">
                        <label>-</label>
                        <input class="calendar" name="expire" type="text" data-rules="{required : true}" data-messages="{required:'失效日期不能为空'}">
                        <input name="id" type="hidden">
                    </div>
                </div>
            </form>
            <div id="grid">
            </div>
        </div>
    </div>
</div>


    <script src="../../resources/lib/bui/js/jquery-1.8.1.min.js"></script>
    <script src="../../resources/lib/bui/js/bui-min.js"></script>
    <script src="../../resources/js/jsdate.js"></script>
    <!-- script start-->
    <script type="text/javascript">
        BUI.use(['bui/form/basefield', 'bui/picker'],function(Field){
            //var Field = BUI.Form.Field;

            /**
             * 表单单选域
             * @class BUI.Form.Field.Radio
             * @extends BUI.Form.Field.Check
             */
            var ClockField = Field.extend({
                //渲染DOM
                renderUI : function(){
                    var _self = this,
                            control = _self.get('control');
                    if(!control){
                        var controlTpl = _self.get('controlTpl'),
                                container = _self.getControlContainer();

                        if(controlTpl){
                            var control = $(controlTpl).appendTo(container);
                            _self.set('control',control);
                        }
                    }else{
                        //var controlContainer = control.parent();
                        _self.set('controlContainer',control.parent());
                    }
                },
                /**
                 * 获取内部表单元素的值
                 * @protected
                 * @param  {jQuery} [innerControl] 内部表单元素
                 * @return {String|Boolean} 表单元素的值,checkbox，radio的返回值为 true,false
                 */
                getControlValue : function(innerControl){
                    var _self = this;
                    innerControl = innerControl || _self.getInnerControl();

                    var inputs = innerControl.children('input');
                    return $(inputs.get(0)).val()+":"+$(inputs.get(1)).val();
                },
                /**
                 * 设置字段的值
                 * @protected
                 * @param {*} value 字段值
                 */
                setControlValue : function(value){
                    var _self = this,
                            innerControl = _self.getInnerControl();
                    var inputs = innerControl.children('input');
                    var hour = value.split(":")[0];
                    var minute = value.split(":")[1];
                    $(inputs.get(0)).val(hour);
                    $(inputs.get(1)).val(minute);
                },
                setInnerWidth : function(width){
                    var _self = this,
                            innerControl = _self.getInnerControl();
                            //appendWidth = innerControl.outerWidth() - innerControl.width();
                    innerControl.children('input').width(14);
                }
            },{
                ATTRS : {
                    /**
                     * 内部表单元素的容器
                     * @type {String}
                     */
                    controlTpl : {
                        view : true,
                        value : '<div><input type="text"/>:<input type="text"/></div>'
                    },
                    /**
                     * 字段的name值
                     * @type {Object}
                     */
                    name : {
                        view :false
                    }
                }
            },{
                xclass : 'form-field-clock'
            });

            var WeekField = Field.extend({
                //渲染DOM
                renderUI : function(){
                    var _self = this,
                            control = _self.get('control');
                    if(!control){
                        var controlTpl = _self.get('controlTpl'),
                                container = _self.getControlContainer();

                        if(controlTpl){
                            var control = $(controlTpl).appendTo(container);
                            _self.set('control',control);
                        }
                    }else{
                        //var controlContainer = control.parent();
                        _self.set('controlContainer',control.parent());
                    }
                },
                /**
                 * 获取内部表单元素的值
                 * @protected
                 * @param  {jQuery} [innerControl] 内部表单元素
                 * @return {String|Boolean} 表单元素的值,checkbox，radio的返回值为 true,false
                 */
                getControlValue : function(innerControl){
                    var _self = this;
                    innerControl = innerControl || _self.getInnerControl();

                    var inputs = innerControl.children('input');
                    var value = [];
                    $.each(innerControl.children('input'), function(i, el){
                        value.push($(el).attr('checked'));
                    });
                    return value;
                },
                /**
                 * 设置字段的值
                 * @protected
                 * @param {*} value 字段值
                 */
                setControlValue : function(value){
                    var _self = this,
                            innerControl = _self.getInnerControl();
                    if (value) {
                        $.each(innerControl.children('input'), function(i, el){
                            $(el).attr("checked", value[i]);
                        });
                    }
                },
                setInnerWidth : function(width){
                    var _self = this,
                            innerControl = _self.getInnerControl();
                    //appendWidth = innerControl.outerWidth() - innerControl.width();
                    //innerControl.children('input').width(14);
                }
            },{
                ATTRS : {
                    /**
                     * 内部表单元素的容器
                     * @type {String}
                     */
                    controlTpl : {
                        view : true,
                        value : '<div class="week"><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/></div>'
                    },
                    /**
                     * 字段的name值
                     * @type {Object}
                     */
                    name : {
                        view :false
                    }
                }
            },{
                xclass : 'form-field-week'
            });
        });

        BUI.use(['bui/grid','bui/data','bui/form/clockfield','bui/form', 'bui/list'],function(Grid,Data,Form,List){
            var Store = Data.Store;

            var timeRegExp = /^(([01]?[0-9])|(2[0-3])):[0-5]?[0-9]$/;
            var startValidator = function(value,obj){
                if (!value || value=='') {
                    return '开始时间不能为空！'
                }
                if (!timeRegExp.test(value)) {
                    return '开始时间格式错误！'
                }
            };
            var endValidator = function(value,obj){
                if (!obj.end || obj.end=='') {
                    return '结束时间不能为空！'
                }
                if (!timeRegExp.test(obj.end)) {
                    return '结束时间格式错误！'
                }

                if (obj.start && timeRegExp.test(obj.start)) {
                    var start = obj.start.split(":");
                    var end = value.split(":");
                    var startHour = parseInt(start[0]);
                    var startMinute = parseInt(start[1]);
                    var endHour = parseInt(end[0]);
                    var endMinute = parseInt(end[1]);
                    //alert(start[0] + "," + start[1] + "," + end[0] + "," + end[1]);
                    if ((endHour * 60 + endMinute) < (startHour * 60 + startMinute)) {
                        return '开始时间应该在结束时间之前！'
                    }
                }

            };
            var timeRender = function(d) {
                if (d) {
                    return new Date(d).pattern("HH:mm");
                } else {
                    return '';
                }
            };

            var datetimeRender = function(d) {
                if (d) {
                    return new Date(d).pattern("yyyy-MM-dd HH:mm");
                } else {
                    return '';
                }
            };
            Grid.Format.dateFormatRenderer = function(d) {
                if (!d) {
                    return '';
                }
                if (BUI.isString(d)) {
                    return d;
                }
                var date = null;
                try {
                    date = new Date(d);
                } catch (e) {
                    return '';
                }
                if (date) {
                    return date.pattern("yyyy-MM-dd HH:mm");
                } else {
                    return '';
                }
            };

            var checkBoxObj = {'true': '是', 'false' : '否'};

            var columns = [
                {title : '时间域名称', dataIndex :'name',editor : {xtype : 'text', rules : {required : true}}},
                {title : '开始时间', dataIndex : 'start', width: 60, editor : {xtype : 'clock', validator : startValidator} },
                {title : '结束时间',dataIndex :'end', width: 60,editor : {xtype : 'clock', validator : endValidator}},
                {title : '星期(1-7)', dataIndex :'week', width:130,editor : {xtype : 'week'},
                    renderer: function(value) {
                        //return '<div class="week"><label class="checkbox"><input type="checkbox"/></label><label class="checkbox"><input type="checkbox"/>二</label></div>';
                        if (!value) {
                            value = [true, true, true, true, true, false, false];
                        }

                        var stringBuilder = [];
                        stringBuilder.push('<div class="week">');
                        for (var i = 0; i < value.length; i++) {
                            var checked = value[i];
                            if (checked) {
                                stringBuilder.push('<input disabled checked type="checkbox"/>');
                            } else {
                                stringBuilder.push('<input disabled type="checkbox"/>');
                            }
                        }
                        stringBuilder.push('</div>');
                        return stringBuilder.join("");
                    }
                },
                {title : '操作',dataIndex:'e', width: 60, renderer : function(){
                    return '<span class="grid-command btn-edit">编辑</span>'
                }}
            ];

            var data = [
                {name:'上午',start:'08:00', end:'12:00',week:[true, true, true, true, true, false, false]},
                {name:'下午',start:'12:30', end:'17:30'}
            ];

            var editing = new Grid.Plugins.RowEditing({
                        triggerCls : 'btn-edit',
                        triggerSelected : false
                    });
            var store = new Store({
                data : data,
                autoLoad:true
            });
            var grid = new Grid.Grid({
                render:'#grid',
                columns : columns,
//                width : 800,
                forceFit : true,
                tbar:{ //添加、删除
                    items : [{
                        btnCls : 'button button-small',
                        text : '<i class="icon-plus" ></i>添加',
                        listeners : {
                            'click' : addFunction
                        }
                    },
                        {
                            btnCls : 'button button-small',
                            text : '<i class="icon-remove"></i>删除',
                            listeners : {
                                'click' : delFunction
                            }
                        }]
                },
                plugins : [editing, Grid.Plugins.CheckSelection],
                store : store
            });

            grid.render();

//添加记录
            function addFunction(){
                var newData = {name : '新建'};
                store.addAt(newData,0);
                editing.edit(newData,'name'); //添加记录后，直接编辑
            }
//删除选中的记录
            function delFunction(){
                var selections = grid.getSelection();
                store.remove(selections);
            }
        });

        var List = BUI.List;
        var items = [
                    {text:'时间域组1',value:'1'},
                    {text:'时间域组2',value:'2'},
                    {text:'时间域组3',value:'3'},
                    {text:"时间域组4",value:4}
                ],
                list = new List.SimpleList({
                    elCls:'bui-select-list',//默认是'bui-simple-list'
                    width:'100%',
                    render : '#time_group_list',
                    items : items
                });
        list.render();
        list.on('selectedchange', function(){
            //alert(list.getSelectedText() + '：' + list.getSelectedValue());
            // todo: 完成其它表单参数获取
            var data = {name:list.getSelectedText()};
            var form = $('#time_group_form')[0];
            BUI.FormHelper.setFields(form,data);
        });

        var Form = BUI.Form;
        new Form.Form({
            srcNode : '#time_group_form'
        }).render();

    </script>
    <!-- script end -->
</body>
</html>